﻿using System;
using System.Linq;
using System.Web.Mvc;
using CharacterCreation.Business.Calculations;
using CharacterCreation.Business.Repositories.Contracts;
using CharacterCreation.Business.ViewModels;
using CharacterCreation.Data.Models;

namespace CharacterCreation.Business.Repositories
{
    public class CharacterRepository : Repository<VMCharacter, Character>, ICharacterRepository
    {
        private Repository<VMCharacterStatistic, CharacterStatistic> reposStats;

        public override void Add(VMCharacter viewModel)
        {
            if (viewModel.Id == Guid.Empty) viewModel.Id = Guid.NewGuid();

            foreach (var charStat in viewModel.Statistics)
            {
                charStat.TotalXP = 0;
                SaveCharacterStatistic(charStat);
            }

            base.Add(viewModel);
        }

        public override VMCharacter Get(Guid id)
        {
            var character = base.Get(id);
            character.Statistics = character.Load(c => c.Statistics);

            return character;
        }

        public override void Update(VMCharacter entity)
        {
            foreach (var charStat in entity.Statistics)
            {
                SaveCharacterStatistic(charStat);
            }

            base.Update(entity);
        }

        public VMCharacterStatistic GetCharacterStatistic(Guid id)
        {
            return reposStats.Get(id);
        }

        public void SaveCharacterStatistic(VMCharacterStatistic statistic)
        {
            statistic.Total = LevelCalculations.CalculateStatistic(
                    statistic.RolledValue + statistic.MovedValue + statistic.RaceBonus, statistic.TotalXP);
            statistic.Information = StatisticRepository.GetStatisticValue(statistic.Name, statistic.Total);

            if (statistic.Id == Guid.Empty) reposStats.Add(statistic);
            else reposStats.Update(statistic);
        }

        public void SaveCharacterStatistic(Guid characterStatisticId)
        {
            var r = RepositoryFactory.Create<VMCharacterStatisticXPDetail>();
            VMCharacterStatistic characterStatistic = GetCharacterStatistic(characterStatisticId);
            if (characterStatisticId != null)
            {
                characterStatistic.TotalXP = r
                    .Get(string.Format("CharacterStatisticId = '{0}'", characterStatisticId))
                    .Sum(xp => xp.XP);
                characterStatistic.Total = LevelCalculations.CalculateStatistic(
                    characterStatistic.RolledValue + characterStatistic.MovedValue + characterStatistic.RaceBonus,
                    characterStatistic.TotalXP);
                reposStats.Update(characterStatistic);
            }
        }

        public CharacterRepository()
        {
            reposStats = new Repository<VMCharacterStatistic, CharacterStatistic>();
        }
    }
}
